import random
from datetime import datetime, timedelta
import time
from flask import current_app
from flask import g
from flask import redirect
from flask import render_template, jsonify
from flask import request
from flask import session
from sqlalchemy import not_

from info import constants, db
from info.models import User, Category, News
from info.utils.common import admin_login_data
from info.utils.response_code import RET
from . import admin_blue


@admin_blue.route('/news_review')
@admin_login_data
def news_review():
    """
    还是查询，分页查询
    :return:
    """
    user = g.user
    try:
        p = request.args.get('p', '1')
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    total_page = 1
    current_page = 1
    news_list = []
    try:
        # # 给新闻添加user_id
        # new_all = News.query.all()
        # for news_one in new_all:
        #     if news_one.user_id > 1:
        #         news_one.user_id = random.randint(2,100)
        #         news_one.status = random.choice([-1, 0, 1])
        # db.session.commit()
        paginate = News.query.filter(not_(News.user_id == user.id)).order_by(News.status, News.id).paginate(p,
                                                            constants.ADMIN_USER_PAGE_MAX_COUNT,False)
        total_page = paginate.pages
        current_page = paginate.page
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)
    news_lists = []
    for news in news_list:
        news_lists.append(news.to_review_dict())

    return render_template('admin/news_review.html', data={
        'total_page':total_page,
        'current_page':current_page,
        "news_list":news_lists
    })


@admin_blue.route('/add_category', methods=['POST', 'GET'])
def news_type():
    """
    从数据库查询所有的新闻分类，返回给前台
    接受两个参数，如果id为空的话，说明是增加分类
    :return:
    """
    categories_model = ''
    try:
        categories_model = Category.query.filter(Category.id > 1).all()
    except Exception as e:
        current_app.logger.error(e)
    categories = []
    for category in categories_model:
        categories.append(category.to_dict())
    if request.method == 'GET':
        return render_template("admin/news_type.html", data={'categories':categories})
    category_id = request.json.get('id', '')
    category_name = request.json.get('name', '')
    # if not category_name:
    #     return jsonify(errno=RET.DATAERR, errmsg='参数错误')
    if category_id:
        category_id = int(category_id)
        try:
            category = Category.query.get(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
        if not category:
            # 这里我们修改一个逻辑，就是修改分类为空视为删除
            return jsonify(errno=RET.DATAERR, errmsg='分类不存在')
        if category_name:
            category.name = category_name
        else:
            db.session.delete(category)
    else:
        category = Category()
        category.name = category_name
        db.session.add(category)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据保存错误')
    return jsonify(errno=RET.OK, errmsg='分类操作成功')


@admin_blue.route("/user_list")
def user_list():
    """
    查询所有用户，分页查询
    :return:
    """
    try:
        p = request.args.get('p', '1')
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    total_page = 1
    current_page = 1
    users = []
    try:
        paginate = User.query.filter(User.is_admin==False).order_by(User.last_login.desc()).paginate(p,
                                                            constants.ADMIN_USER_PAGE_MAX_COUNT,False)
        total_page = paginate.pages
        current_page = paginate.page
        users = paginate.items
    except Exception as e:
        current_app.logger.error(e)
    user_lists = []
    for user in users:
        user_lists.append(user.to_admin_dict())
    return render_template('admin/user_list.html', data={
        'total_page':total_page,
        'current_page':current_page,
        "user_list":user_lists
    })


@admin_blue.route("/user_count")
def user_count():
    # 查询总人数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询月新增数
    mon_count = 0
    try:
        # 月初日期
        now = time.localtime()
        mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        mon_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询日新增数
    day_count = 0
    try:
        now = time.localtime()
        day_begin = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
        day_begin_date = datetime.strptime(day_begin, '%Y-%m-%d')
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询图表信息
    # 获取到当天00:00:00时间

    now_date = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')
    # 定义空数组，保存数据
    active_date = []
    active_count = []

    # 依次添加数据，再反转
    for i in range(0, 31):
        begin_date = now_date - timedelta(days=i)
        end_date = now_date - timedelta(days=(i - 1))
        active_date.append(begin_date.strftime('%Y-%m-%d'))
        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
                                      User.last_login < end_date).count()
        except Exception as e:
            current_app.logger.error(e)
        active_count.append(count)

    active_date.reverse()
    active_count.reverse()

    data = {"total_count": total_count, "mon_count": mon_count, "day_count": day_count, "active_date": active_date,
            "active_count": active_count}
    return render_template("admin/user_count.html", data=data)


@admin_blue.route('/login', methods=['POST', 'GET'])
def login():
    """
    get请求的时候渲染模板
    post请求的时候，接受前台传过来的数据，然后访问数据库对登陆身份进行校验
    如果不成功，显示错误信息
    如果成功，跳转默认页面
    :return:
    """
    if request.method == 'GET':
        user_id = session.get('user_id', None)
        is_admin = session.get('is_admin', False)
        if user_id and is_admin:
            return redirect('/admin/index')
        return render_template('admin/login.html')

    username = request.form.get('username', '')
    password = request.form.get('password', '')
    if not all([username, password]):
        return render_template('admin/login.html', errmsg="参数不足")

    try:
        user = User.query.filter(User.mobile == username).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html', errmsg="数据查询失败")

    if not user:
        return render_template('admin/login.html', errmsg="用户不存在")

    if not user.check_password(password):
        return render_template('admin/login.html', errmsg="密码错误")

    if not user.is_admin:
        return render_template('admin/login.html', errmsg="用户权限错误")

    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    session["is_admin"] = True

    # 跳转到后台管理主页,暂未实现
    return redirect("/admin/index")


@admin_blue.route("/index")
@admin_login_data
def admin_index():
    user = g.user
    if user:
        return render_template('admin/index.html', data = {'user':user.to_dict()})
    return redirect('/admin/login')



